/* eslint-disable no-shadow */
const fs = require('fs')
const path = require('path')
const inquirer = require('inquirer')
const { execSync } = require('child_process')

const resolve = (file) => path.resolve(__dirname, file)
let entries = JSON.parse(fs.readFileSync(resolve('./build/config.entries.json')), 'utf-8')
entries = entries.map(({ value, name }) => (
  { value, name: `${value} (${name})` }
))

inquirer.registerPrompt('autocomplete', require('inquirer-autocomplete-prompt'))

inquirer.prompt([{
  type: 'autocomplete',
  name: 'entry',
  message: '选择开发模块（可搜索）：',
  choices: entries,
  source: (answersSoFar, input) => {
    const kw = input || ''
    return new Promise((resolve) => {
      setTimeout(() => {
        const results = entries.filter(el => el.value.includes(kw))
        resolve(results)
      }, 200)
    })
  },
}]).then((answers) => {
  const { entry } = answers
  const env = Object.create(process.env)
  env.VUE_APP_ENTRY = entry
  execSync('npm run serve', { env, stdio: 'inherit' })
})
